package pl.poznan.put.cs.to.tsp.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileOperations {
	public static Vertexes loadInstance(String fileName) {
		File f = new File(fileName);
		Vertexes v;
		try {
			BufferedReader input = new BufferedReader(new FileReader(f));
			try {
				String line = null;

				line = input.readLine();
				int numberOfNodes = Integer.parseInt(line.split("[^0-9]")[0]);
				// System.out.println(numberOfNodes);
				v = new Vertexes(numberOfNodes);

				for (int i = 0; i < numberOfNodes; i++) {
					line = input.readLine();
					String[] xy = line.split("[^0-9]");
					int x = Integer.parseInt(xy[0]);
					int y = Integer.parseInt(xy[1]);

					v.add(x, y);
					// System.out.println("[" + x + ", " + y + "]");
				}
			} finally {
				input.close();
			}
		} catch (IOException ex) {
			throw new RuntimeException("Instance file not found!", ex);
		}
		return v;
	}

	public static void saveSolutionToFile(IResultHolder heuristic,
			String filename) {
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter(filename));
			out.write(heuristic.getLengthA() + heuristic.getLengthB() + "\n");
			out.write(heuristic.getListA().size() + "\n");
			out.write(heuristic.getListB().size() + "\n");
			for (Integer i : heuristic.getListA()) {
				out.write(i + "\n");
			}
			for (Integer i : heuristic.getListB()) {
				out.write(i + "\n");
			}
			out.close();
		} catch (IOException e) {
			throw new RuntimeException("Error while writing to file!", e);
		}
	}

	public static void saveResultToFile(IResultHolder alg, String filename) {
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter(filename));
			out.write(alg.getLengthA() + alg.getLengthB() + "\n");
			out.close();
		} catch (IOException e) {
			throw new RuntimeException("Error while writing to file!", e);
		}
	}
}
